﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Dtos;
using WisDom.SmartTMS.InterFace;
using WisDom.SmartTMS.Entity;
using WisDom.SmartTMS.Data;
using WisDom.SmartTMS.Dto.BusinessAudit;
using WisDom.SmartTMS.Enums;

namespace WisDom.SmartTMS.Services
{
    /// <summary>
    /// 入职审批功能应用服务实现类
    /// </summary>
    public class VehicleAuditAppService : SmartTMSAppService, IVehicleAuditAppService
    {
        //依赖注入
        private readonly IRepository<PersonnelEntry, Guid> _vehiclesRepository; //人事仓储

        private readonly IBusinessAuditRepository _auditRepository; //审计主表仓储

        public VehicleAuditAppService(IRepository<PersonnelEntry, Guid> vehiclesRepository,
                                      IBusinessAuditRepository auditRepository)
        {
            _vehiclesRepository = vehiclesRepository;
            _auditRepository = auditRepository;
        }

        /// <summary>
        /// 终止审批（通过/拒绝）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task EndAuditAsync(ProcessBusinessAuditDto input)
        {
            //获取审核主信息
            Audit auditInfo = await _auditRepository.GetAuditById(input.AuditId, BusinessType.Vehicle)
                                                    .SingleOrDefaultAsync();

            //终止审批(input.State为通过或拒绝）
            auditInfo.EndAudit((Guid)CurrentUser.Id, CurrentUser.UserName, input.State, input.Remark);

            //持久化（todo）
            await _auditRepository.UpdateAsync(auditInfo);

            await UnitOfWorkManager.Current.SaveChangesAsync();  //完成工作单元
        }

        /// <summary>
        /// 查看所有审核主记录(不带条件分页）--如果要带查询条件-自己思考
        /// </summary>
        /// <returns></returns>
        public async Task<PagedResultDto<VehicleAuditDto>> GetVehicleAuditAsync(PagedAndSortedResultRequestDto input)
        {
            //车辆表和审核表联查
            var query = from v in _vehiclesRepository   //车辆信息
                        join a in _auditRepository.GetAuditList(BusinessType.Vehicle) //车辆审核信息
                        on v.Id equals a.BusinessId     //连接条件
                        orderby v.Id
                        select new VehicleAuditDto
                        {
                            
                        };

            //获取总条数
            var totalCount = await query.CountAsync();

            //从仓储获取实体数据对象
            List<VehicleAuditDto> vehicleAudits = await query.Skip(input.SkipCount)
                                                        .Take(input.MaxResultCount)
                                                        .ToListAsync();

            //返回分页结果集
            return new PagedResultDto<VehicleAuditDto>(totalCount, vehicleAudits);
        }


        /// <summary>
        /// 根据主记录Id获取主记录信息
        /// </summary>
        /// <param name="auditId"></param>
        /// <returns></returns>
        public async Task<VehicleAuditLogDto> GetVehicleAuditByIdAsync(Guid auditId)
        {
            //车辆表和审核表联查
            var query = from v in _vehiclesRepository   //车辆信息
                        join a in _auditRepository.GetAuditById(auditId, BusinessType.Vehicle) //单个车辆审核信息
                        on v.Id equals a.BusinessId     //连接条件
                        select new VehicleAuditLogDto
                        {
                            Brand = v.EntryName,
                            Driver = v.DepId,
                            LicensePlate = v.Position,
                            AudiLogtDtos = ObjectMapper.Map<List<AuditLog>, List<AudiLogtDto>>(a.AuditLogs)
                            
                        };

            return await query.SingleOrDefaultAsync();  //返回
        }

        /// <summary>
        /// 通过并转批
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task ProcessAuditAsync(ProcessBusinessAuditDto input)
        {
            //拿到审批主记录
            Audit auditInfo = await _auditRepository.GetAuditById(input.AuditId, BusinessType.Vehicle)
                                                    .SingleOrDefaultAsync();

            //当前审核人处理审批
            auditInfo.ProcessAudit((Guid)CurrentUser.Id, CurrentUser.Name, input.Remark);

            //持久化（更新主信息）
            await _auditRepository.UpdateAsync(auditInfo);

            //新增下一个人审批日志
            auditInfo.AddAuditLog((Guid)input.NextPersonId, GuidGenerator.Create(), input.NextPersonName);

            //持久化

            await UnitOfWorkManager.Current.SaveChangesAsync();  //完成工作单元
        }
    }
}
